import pygame,sys,os
from pygame.locals import *

class ResourceManager(object):

   BASE_NAME = 0
   FRAMES = 1
   animationList = [ ('EG_Idle',2),
                     ('EG_WalkSide',8),
                     ('EG_Punch',3),
                     ('EG_Kick',5),
                     ('Kid_Run',2),
                     ('Kid_Bite',2),
                     ('Kid_Dead',1)]  

   soundList = ['EG_Kick',
                'EG_Punch',
                'EG_Eat',
                'EG_Flame',
                'Kid_Crunch',
                'Kid_Bite',
                'Kid_Die']

   def __init__(self):
      self.animations = {}
      self.sounds = {}
      

   def loadResources(self):
      self.loadAnimations()
      self.loadSounds()


# Name: loadAnimations
# Description:
#      Iterates over the animation list, loading the frames of each animation from files and adding them (and their horizontal flips) to the dictionary of animations.
#       File animations are facing right, and are flipped to provide left facing animations.
   def loadAnimations(self):
      for animation in self.animationList:
         animRight = []
         animLeft = []
         for frame in range(animation[self.FRAMES]):
            fullname = animation[self.BASE_NAME] + '_' + str(frame)
            image = self.loadImage(fullname + '.png', -1)
            animRight.append(image)
            animLeft.append(pygame.transform.flip(image,True,False))
         self.animations[animation[self.BASE_NAME] + "_Right"] = animRight
         self.animations[animation[self.BASE_NAME] + "_Left"] = animLeft


# Name: loadImage
# Description:
#      Loads an image from a file in the subdirectory 'data'. Exits program if image is not found.
#      Sets the colorkey (transparent color) as the color in the topleft corner if colorkey = -1
   def loadImage(self, name, colorkey=None):
       fullname = os.path.join('images',name)
       try:
           image = pygame.image.load(fullname)
       except pygame.error, message:
           print 'Cannot load image:', name
           raise SystemExit, message
       image = image.convert()
       if colorkey is not None:
           if colorkey is -1:
               colorkey = image.get_at((0,0))
           image.set_colorkey(colorkey, RLEACCEL)
       return image

   def getAnimation(self, name):
      return self.animations[name]

   def getImage(self, name):
      return self.animations[name][frame]
         
                     


   def loadSounds(self):
      for sound in self.soundList:
         fullname = os.path.join('sounds',sound)
         try:
            loadedSound = pygame.mixer.Sound(fullname + '.wav')
         except pygame.error, message:
            print 'Cannot load sound:', sound
            raise SystemExit, message
         if sound != 'EG_Flame':
            loadedSound.set_volume(0.5)
         self.sounds[sound] = loadedSound

   def getSound(self,soundName):
      return self.sounds[soundName]
